﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using kxcxw.Data;
using System.Collections;
using kxcxw.Data.Entities;
using System.Web.Security;
using System.IO;
using kxcxw.Business;
using System.Xml;
using System.Xml.Linq;
using System.Text;
using Webdiyer.WebControls.Mvc;
using KXCXW.Web.CommonClass;
using kxcxw.Data.Common;
using System.Data;
using KXCXW.Web.Models;
using System.Web.Caching;

namespace KXCXW.Web.Controllers
{
    public class AdController : Controller
    {
        //
        // GET: /Ad/
        private KXCXWDBContext db = new KXCXWDBContext();
        private CommonRepositories comm = new CommonRepositories();

        [Authorize]
        public ActionResult MyAd(string sortOrder, string searchString, string type, int? page = 1)
        {
            ViewData["dlCount"] = "0";
            if (type == null) type = "W";
            ViewData["type"] = type;

            #region 我的信息
            string userid = Membership.GetUser().ProviderUserKey.ToString();
            ViewBag.DateSortParm = sortOrder == "Date" ? "Date desc" : "Date";
            var ad = from s in db.AdApplys where s.UserID == userid && s.AdBlockId.Contains(type) select s;
            if (!String.IsNullOrEmpty(searchString))
            {
                ad = ad.Where(s => s.AltText.ToUpper().Contains(searchString.ToUpper()));
            }
            switch (sortOrder)
            {
                case "Date":
                    ad = ad.OrderBy(s => s.CreateDate);
                    break;
                default:
                    ad = ad.OrderByDescending(s => s.CreateDate);
                    break;
            }
            int pageSize = 10;
            int pageIndex = page ?? 1;
            PagedList<AdApply> temp = ad.ToPagedList(pageIndex, pageSize);
            if (Request.IsAjaxRequest())
                return PartialView("List", temp);
            #endregion
            return View(temp);
        }

        [Authorize]
        public ActionResult SelectShopType()
        {
            return View();
        }

        [Authorize]
        public ActionResult SelectBlock(string id)
        {
            ViewData["shoptype"] = id;
            return View();
        }

        [Authorize]
        public ActionResult Apply(string shoptype, string blockid)
        {
            ViewData["shoptype"] = shoptype;
            string rootpath = Server.MapPath("~/Content/xml/Adconfig.xml");
            AdHelper ah = new AdHelper(rootpath, shoptype, blockid);
            List<SelectListItem> Items = new List<SelectListItem>();
            Items.Add(new SelectListItem { Value = "", Text = "请选择广告位" });
            List<AdModel> adlist = ah.getAdConfigList();
            foreach (AdModel am in adlist)
                Items.Add(new SelectListItem { Value = am.id, Text = am.name });
            ViewBag.AdBlockList = Items;
            ViewBag.BlockDesc = ah.blockdesc;
            ViewBag.width = adlist.FirstOrDefault().width;
            ViewBag.height = adlist.FirstOrDefault().height;
            AdApply ad = new AdApply();
            ad.AdId = Guid.NewGuid().ToString();
            ad.EffectiveDays = 180;
            ad.CreateDate = DateTime.Now;
            ad.Status = 0;
            ad.UserID = "";
            if (Membership.GetUser() != null)
            {
                ad.UserID = Membership.GetUser().ProviderUserKey.ToString();
                ad.ApplyerName = Membership.GetUser().UserName;
            }
            return View(ad);
        }

        [Authorize]
        [HttpPost]
        public ActionResult Apply(AdApply adApply)
        {
            string rootpath = Server.MapPath("~/Content/xml/Adconfig.xml");
            AdHelper ah = new AdHelper(rootpath, adApply.AdBlockId[0].ToString(), adApply.AdBlockId[1].ToString());
            List<SelectListItem> Items = new List<SelectListItem>();
            Items.Add(new SelectListItem { Value = "", Text = "请选择广告位" });
            AdModel adModel = null;
            foreach (AdModel am in ah.getAdConfigList())
            {
                SelectListItem item = new SelectListItem { Value = am.id, Text = am.name };
                if (adApply.AdBlockId == am.id)
                {
                    item.Selected = true;
                    adModel = am;
                }
                Items.Add(item);
            }
            if (ModelState.IsValid)
            {
                HttpPostedFileBase file = Request.Files["ImgName"];
                if (file != null)
                {
                    try
                    {
                        string fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
                        if (ImgUpLoadHelper.SavePicFormat(Server.MapPath("~/" + AdHelper.ImgRootUrl), fileName, adModel.width, adModel.height, file)!="")
                        {
                            adApply.CreateDate = DateTime.Now;
                            adApply.ApprovalDate = DateTime.Now;
                            adApply.ImgName = fileName;
                            db.AdApplys.Add(adApply);
                            db.SaveChanges();
                            return RedirectToAction("ApplySuccess");
                        }
                        else
                        {
                            ModelState.AddModelError("file", "图片上传失败！");
                        }
                    }
                    catch (Exception ex)
                    {
                        ModelState.AddModelError("exception", "出现异常！");
                    }
                }
                else
                {
                    ModelState.AddModelError("file", "没选择广告图片！");
                }
            }
            ViewBag.AdBlockList = Items;
            ViewBag.BlockDesc = ah.blockdesc;
            ViewBag.width = adModel.width;
            ViewBag.height = adModel.height;
            adApply.UserID = "";
            if (Membership.GetUser() != null)
            {
                adApply.UserID = Membership.GetUser().ProviderUserKey.ToString();
                adApply.ApplyerName = Membership.GetUser().UserName;
            }
            return View(adApply);
        }

        public ActionResult ApplySuccess()
        {
            return View();
        }

        [Authorize]
        public ActionResult Edit(string id)
        {
            AdApply ad = db.AdApplys.Find(id);
            string rootpath = Server.MapPath("~/Content/xml/Adconfig.xml");
            AdHelper ah = new AdHelper(rootpath, ad.AdBlockId[0].ToString(), ad.AdBlockId[1].ToString());
            List<SelectListItem> Items = new List<SelectListItem>();
            Items.Add(new SelectListItem { Value = "", Text = "请选择广告位" });
            List<AdModel> adlist = ah.getAdConfigList();
            foreach (AdModel am in adlist)
            {
                SelectListItem list = new SelectListItem { Value = am.id, Text = am.name };
                if (ad.AdBlockId == am.id)
                    list.Selected = true;
                Items.Add(list);
            }
            ViewBag.AdBlockList = Items;
            ViewBag.BlockDesc = ah.blockdesc;
            ViewBag.width = adlist.FirstOrDefault().width;
            ViewBag.height = adlist.FirstOrDefault().height;
            return View(ad);
        }

        //
        // POST: /Activity/Edit/5

        [Authorize]
        [HttpPost]
        public ActionResult Edit(AdApply adApply)
        {
            string rootpath = Server.MapPath("~/Content/xml/Adconfig.xml");
            AdHelper ah = new AdHelper(rootpath, adApply.AdBlockId[0].ToString(), adApply.AdBlockId[1].ToString());
            List<SelectListItem> Items = new List<SelectListItem>();
            Items.Add(new SelectListItem { Value = "", Text = "请选择广告位" });
            AdModel adModel = null;
            foreach (AdModel am in ah.getAdConfigList())
            {
                SelectListItem item = new SelectListItem { Value = am.id, Text = am.name };
                if (adApply.AdBlockId == am.id)
                {
                    item.Selected = true;
                    adModel = am;
                }
                Items.Add(item);
            }
            if (ModelState.IsValid)
            {
                HttpPostedFileBase file = Request.Files["file"];
                string fileName = "";
                try
                {
                    if (file != null && file.FileName != "")
                    {
                        fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
                        if (ImgUpLoadHelper.SavePicFormat(Server.MapPath("~/" + AdHelper.ImgRootUrl), fileName, adModel.width, adModel.height, file)!="")
                        {
                            adApply.ImgName = fileName;
                        }
                        else
                        {
                            ModelState.AddModelError("file", "图片上传失败！");
                        }
                    }
                    adApply.Status = DataConstants.pending;
                    db.Entry(adApply).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("EditSuccess");
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("exception", "出现异常！");
                }
            }
            return View(adApply);
        }


        public ActionResult EditSuccess(string id)
        {
            return View();
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
